package com.qbccn.bbs.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.qbccn.bbs.domain.BbsFile;
import com.qbccn.bbs.domain.BbsUser;
import com.qbccn.bbs.dto.ResponseResult;
import com.qbccn.bbs.mapper.BbsFileMapper;
import com.qbccn.bbs.mapper.BbsUserMapper;
import com.qbccn.bbs.service.FileService;
import com.qbccn.bbs.service.UserService;
import com.qbccn.bbs.utils.CommonUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author linke
 * @date 2020/6/13 1:13
 * @description
 */
@Service
public class FileServiceImpl implements FileService {


  @Value("${oss.aliyun.bucket}")
  private String bucket;
  @Value("${oss.aliyun.endPoint}")
  private String endPoint;
  @Value("${oss.aliyun.accessKeyId}")
  private String accessKeyId;
  @Value("${oss.aliyun.accessKeySecret}")
  private String accessKeySecret;


  @Autowired
  private HttpServletRequest request;
  @Autowired
  private UserService userService;
  @Autowired
  private BbsUserMapper bbsUserMapper;
  @Autowired
  private BbsFileMapper bbsFileMapper;

  @Transactional
  @Override
  public synchronized ResponseResult uploadImgToAliyunOss(MultipartFile multiFile, int actionType)
      throws IOException {
    if (multiFile.isEmpty()) {
      return new ResponseResult(1, "请选择图片");
    }
    // 获取上传的文件
    long fileSize = multiFile.getSize();
    if (fileSize > 524288) {
      return new ResponseResult(1, "图片大小不能超过500KB");
    }
    String originalName = multiFile.getOriginalFilename();
    String suffix = originalName.substring(originalName.lastIndexOf("."), originalName.length());
    //判断后缀
    if (!suffix.equals(".jpg") && !suffix.equals(".png") && !suffix.equals(".gif") && !suffix
        .equals(".jpeg")) {
      return new ResponseResult(1, "图片格式有误。支持：.jpg、.png、gif、jpeg");
    }
    BbsUser user = (BbsUser) request.getSession().getAttribute("user");
    String currentTime = String.valueOf(System.currentTimeMillis());

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentType(getContentType(suffix));
    // 上传文件流。
    InputStream inputStream = multiFile.getInputStream();
    String fileName = "img/" + currentTime + suffix;
    ossClient.putObject(bucket, fileName, inputStream, objectMetadata);
    // 关闭OSSClient。
    ossClient.shutdown();

    //注意加上 http://
    String url = String.format("http://%s.%s/%s", bucket, endPoint, fileName);
    BbsFile bbsFile = new BbsFile();
    bbsFile.setServerPath("img/");
    bbsFile.setUrl(url);
    bbsFile.setActionType(actionType);
    bbsFile.setCreateTime(new Date());
    bbsFile.setFileSize(Integer.valueOf((int) multiFile.getSize()));
    bbsFile.setStatus(1);
    bbsFile.setIp(CommonUtils.getIpAddress(request));
    if (multiFile.getOriginalFilename().length() > 49) {
      bbsFile.setOriginalName(multiFile.getOriginalFilename().substring(0, 45) + suffix);
    } else {
      bbsFile.setOriginalName(multiFile.getOriginalFilename());
    }
    bbsFile.setUsername(user.getUsername());
    bbsFileMapper.insertSelective(bbsFile);
    bbsUserMapper.updateImg(user.getUsername(), url);
    //更新session中的user
    user.setImgUrl(url);
    request.getSession().setAttribute("user", user);
    return new ResponseResult(0, "success", url);
  }

  public static String getContentType(String suffix) {
    if (suffix.equalsIgnoreCase(".jpeg") ||
        suffix.equalsIgnoreCase(".jpg") ||
        suffix.equalsIgnoreCase(".png")) {
      return "image/jpg";
    }
    if (suffix.equalsIgnoreCase(".gif")) {
      return "image/gif";
    }
    if (suffix.equalsIgnoreCase(".bmp")) {
      return "image/bmp";
    }
    if (suffix.equalsIgnoreCase(".html")) {
      return "text/html";
    }
    if (suffix.equalsIgnoreCase(".txt")) {
      return "text/plain";
    }
    if (suffix.equalsIgnoreCase(".vsd")) {
      return "application/vnd.visio";
    }
    if (suffix.equalsIgnoreCase(".pptx") ||
        suffix.equalsIgnoreCase(".ppt")) {
      return "application/vnd.ms-powerpoint";
    }
    if (suffix.equalsIgnoreCase(".docx") ||
        suffix.equalsIgnoreCase(".doc")) {
      return "application/msword";
    }
    if (suffix.equalsIgnoreCase(".xml")) {
      return "text/xml";
    }
    return "image/jpg";
  }
}
